//
//  HJDecimalPadKeyboard.m
//  KaiChat
//
//  Created by lx on 2024/1/25.
//

#import "HJDecimalPadKeyboard.h"
#import "UITextField+Category.h"


@interface HJKeyBoardButton : UIButton


@end


@implementation HJKeyBoardButton

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.addCornerRadius(10);
        [self setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        self.titleLabel.font = [UIFont systemFontOfSize:23 weight:UIFontWeightSemibold];
        [self setBackgroundImage:[UIImage imageWithColor:UIColor.whiteColor] forState:UIControlStateNormal];
        [self setBackgroundImage:[UIImage imageWithColor:UIColor.tj_F6F6F6Color] forState:UIControlStateHighlighted];
    }
    return self;
}

@end


@interface HJDecimalPadKeyboard()

@property (nonatomic, weak) UITextField *textField;

@end


@implementation HJDecimalPadKeyboard

+ (instancetype)keyboard {
    return [[HJDecimalPadKeyboard alloc] init];
}

- (void)setFrame:(CGRect)frame {
    frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 260 + TabbarSafeBottomMargin);
    [super setFrame:frame];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = UIColor.redColor;
        [self layoutUI];
    }
    return self;
}


- (void)shuffleArray:(NSMutableArray *)array {
    NSUInteger count = [array count];
    if (count > 1) {
        for (NSUInteger i = 0; i < count - 1; i++) {
            NSUInteger j = arc4random_uniform((uint32_t)(count - i)) + i;
            if (i != j) {
                [array exchangeObjectAtIndex:i withObjectAtIndex:j];
            }
        }
    }
}
 
- (void)layoutUI {

    self.backgroundColor = UIColor.whiteColor;
    
    NSMutableArray *numberArray = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"].mutableCopy;
//    [self shuffleArray:numberArray];
    
    NSMutableArray *textArray = [NSMutableArray array];
    [textArray addObjectsFromArray:[numberArray subarrayWithRange:NSMakeRange(0, numberArray.count - 1)]];
    [textArray addObject:@""];
    [textArray addObject:numberArray.lastObject];
    [textArray addObject:@"delete"];
    
    NSInteger numberOfRows = 4;
    NSInteger numberOfColumns = 3;
    CGFloat padding = 15;

    CGFloat width = (UIScreen.mainScreen.bounds.size.width - padding * 2 - leftRightMargin * 2) / 3;
    CGFloat buttonH = 50;

       for (NSInteger row = 0; row < numberOfRows; row++) {
           for (NSInteger col = 0; col < numberOfColumns; col++) {
               
               NSInteger index = row * numberOfColumns + col;
               NSString *textStr = textArray[index];
               
               HJKeyBoardButton *button = [HJKeyBoardButton addToView:self];
               if ([textStr isEqualToString:@"delete"]) {
                   [button setImage:[UIImage imageNamed:@"keyboard_delete"] forState:UIControlStateNormal];
                   [button addTarget:self action:@selector(didClickDeleteButton) forControlEvents:UIControlEventTouchUpInside];
               } else {
                   button.titleLabel.font = UIFontSemiboldMake(23);
                   button.titleLabel.textColor = UIColor.tj_333333Color;
                   if (![textStr isEqualToString:@""]) {
                       [button setTitle:textStr forState:UIControlStateNormal];
                       [button addTarget:self action:@selector(didClickDigitalButton:) forControlEvents:UIControlEventTouchUpInside];
                   } else {
                       button.userInteractionEnabled = NO;
                   }
               }
               button.frame = CGRectMake(leftRightMargin + col * (width + padding), padding + row * (buttonH + padding), width, buttonH);
           }
       }
        
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidBeginEditing:) name:UITextFieldTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidEndEditing:) name:UITextFieldTextDidEndEditingNotification object:nil];

}

- (void)textDidEndEditing:(NSNotification *)notification {
    [self.textField resignFirstResponder];
}

- (void)textFieldDidBeginEditing:(NSNotification *)notification {
    self.textField = notification.object;
}

- (void)textFieldDidChange:(UITextField *)textField {
//    _doneButton.enabled = textField.text.length;
    [textField sendActionsForControlEvents:UIControlEventEditingChanged];
    [[NSNotificationCenter defaultCenter] postNotificationName:UITextFieldTextDidChangeNotification object:textField];
}

- (void)setDoneText:(NSString *)doneText {
    
}

- (void)didClickDeleteButton {
    
    NSRange nowRange = self.textField.selectedRange;
    NSMutableString *oldString = [[NSMutableString alloc]initWithString:self.textField.text];
//
//    if (nowRange.location == 0) {
//        return;
//    }
    
    if (nowRange.length == 0) {
        nowRange.length = 1;
        nowRange.location --;
    }
    if (self.textField.text.length>0) {
        if ([self.textField.delegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) {
            BOOL isEdit = [self.textField.delegate textField:self.textField shouldChangeCharactersInRange:nowRange replacementString:@""];
            if (isEdit) {
                [oldString replaceCharactersInRange:nowRange withString:@""];
                self.textField.text = oldString;
                nowRange.length = 0;
                self.textField.selectedRange = nowRange;
            }
        }else {
            [oldString replaceCharactersInRange:nowRange withString:@""];
            self.textField.text = oldString;
            nowRange.length = 0;
            self.textField.selectedRange = nowRange;
        }
    }

    [self textFieldDidChange:self.textField];
}

- (BOOL)resignFirstResponder {
    [self.textField resignFirstResponder];
    return [super resignFirstResponder];
}

- (void)didClickDoneButton {
    if ([self.textField.delegate respondsToSelector:@selector(textFieldShouldReturn:)]) {
        if ([self.textField.delegate textFieldShouldReturn:_textField]) {
            [self.textField resignFirstResponder];
        }
    } else {
        [self.textField resignFirstResponder];
    }
}

- (void)didClickDigitalButton:(UIButton *)button {
    
    NSString *text = button.currentTitle;
    
    NSRange nowRange = self.textField.selectedRange;
    NSMutableString *oldText = [[NSMutableString alloc]initWithString:self.textField.text];
    
    if ([self.textField.delegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) {
        BOOL isEdit = [self.textField.delegate textField:self.textField shouldChangeCharactersInRange:self.textField.selectedRange replacementString:text];
        if (isEdit) {
            
            [oldText replaceCharactersInRange:nowRange withString:text];
            self.textField.text = oldText;
            nowRange.location ++;
            nowRange.length = 0;
            self.textField.selectedRange = nowRange;
        }
    }else {
        [oldText replaceCharactersInRange:nowRange withString:text];
        self.textField.text = oldText;
        nowRange.location ++;
        nowRange.length = 0;
        self.textField.selectedRange = nowRange;
    }
 
    [self textFieldDidChange:self.textField];

}
 
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



@end
